package com.atguigu.business.service.impl;

import com.atguigu.business.feign.OrderFeignClient;
import com.atguigu.business.feign.StorageFeignClient;
import com.atguigu.business.service.BusinessService;
import org.apache.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class BusinessServiceImpl implements BusinessService {

    @Autowired
    StorageFeignClient storageFeignClient;

    @Autowired
    OrderFeignClient orderFeignClient;


    /**
     * 二阶提交协议
     * 1.注册全局事务,生成全局事务XID
     * 2.全局事务开始
     * 前镜像 后镜像
     * 全局锁(精据级别)
     * 一阶:本地事务提交(业务数据+undo_log)
     * 二阶:成功+失败
     * 成功:所有人删除undo_log
     * 失败:所有人拿到自己的前镜像,恢复,删除undo_log
     *
     * 购买
     * @param userId            用户id
     * @param commodityCode     商品编号
     * @param orderCount        购买数量
     */
    //解决数据不一致
    @GlobalTransactional
    @Override
    public void purchase(String userId, String commodityCode, int orderCount) {
        //1. 扣减库存
        storageFeignClient.deduct(commodityCode, orderCount);

        //2. 创建订单
        orderFeignClient.create(userId, commodityCode, orderCount);
    }
}
